/**
 * {作业名称}
 *
 * 输入参数:
 *
 * 输出参数:
 *
 */
(() => {
  // 私有区域
  function mapName(name) {
    switch (name) {
      case '仓库.名称':
        return 'B.MC';
      case '品规.商品.类目.名称':
        return 'E.MC';
      case '品规.商品.名称':
        return 'D.MC';
      case '品规.名称':
        return 'C.MC';
      case '品规.条码':
        return 'C.TM';
      default:
        throw Error(`无效字段: ${name}`);
    }
  }

  function parseOrder(order) {
    switch (order) {
      case 'asc':
      case 'ascend':
        return 'ASC';
      case 'desc':
      case 'descend':
        return 'DESC';
      default:
        throw Error(`无效排序方式: ${order}`);
    }
  }

  return function ({ UID, Filter, Order, PageSize, PageNo }) {
    // 验证输入参数
    if (!UID) throw Error("无效会话");

    const params = [];
    const filters = Filter.map(f => {
      const [Field, Op, Value] = f;
      if (Op === '=') params.push(Value);
      else if (Op === 'like') params.push(`%${Value}%`);
      else throw Error(`无效操作符: ${Op}`);
      return `${mapName(Field)} ${Op} ?`;
    });
    if (filters.length === 0) filters.push('1=1');

    const orders = [];
    Object.keys(Order).forEach(key => {
      orders.push(`${mapName(key)} ${parseOrder(Order[key])}`);
    });
    if (orders.length === 0) orders.push('B.MC, E.MC, D.MC, C.MC, C.TM');

    return A.job.Paginate({
      UID,
      Connection: 'MP',
      Text: `SELECT B.MC "仓库.名称", E.MC "品规.商品.类目.名称", D.MC "品规.商品.名称", C.MC "品规.名称", C.TM "品规.条码", C.ID, SUM(A.YL) 余量 FROM ST_KCTZ A, ST_CK B, ST_SPGG C, ST_SP D, ST_LM E WHERE A.YL>0 AND A.CK_ID=B.ID AND A.PG_ID=C.ID AND C.SP_ID=D.ID AND D.LM_ID=E.ID AND ${filters.join(' AND ')} GROUP BY B.MC, E.MC, D.MC, C.MC, C.TM, C.ID ORDER BY ${orders.join(', ')}`,
      Params: params,
      PageSize, PageNo
    });
  };
})()